<template>
  <div class="menu-wrap curr-main">
    <div class="tree-form">
      <div>
        <div class="add-menu">
          <h3 class="menu-list">菜单列表</h3>
          <el-button @click="addMenu()" type="primary" class="add">新增一级菜单</el-button>
        </div>
        <!-- <el-tree :data="menuTreeList" :props="defaultProps" @node-click="handleNodeClick" class="menu-tree" /> -->
        <el-tree :data="menuTreeList" node-key="id" class="menu-tree" highlight-current @node-click="handleNodeClick">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <!-- <span>{{ node }}</span> -->
              <span>{{ data.name }}</span>
              <span>
                <a @click.stop="append(data.id)" class="add-icon">
                  <el-icon class="">
                    <circlePlus />
                  </el-icon>
                </a>
                <a @click.stop="remove(data.id)" class="delete-icon">
                  <el-icon class="">
                    <deleteFilled />
                  </el-icon>
                </a>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80px" class="demo-ruleForm" v-if="ruleFormVisible">
        <h3 class="addForm">{{addValue}}</h3>
        <el-form-item label="pid:" prop="pid">
          <el-input v-model="ruleForm.pid" :disabled="editPid"></el-input>
        </el-form-item>
        <el-form-item label="name:" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="path:" prop="path" v-if="addValue==='新增子级菜单'">
          <el-input v-model="ruleForm.path" :disabled="editPath"></el-input>
        </el-form-item>
        <el-form-item label="icon:" prop="icon">
          <el-input v-model="ruleForm.icon"></el-input>
        </el-form-item>
        <el-form-item label="order:" prop="order">
          <el-input v-model="ruleForm.order"></el-input>
        </el-form-item>
        <div class="btn">
          <el-button type="primary" @click="submitForm()">保存</el-button>
          <el-button @click="ruleFormVisible=false">取消</el-button>
        </div>
      </el-form>
    </div>
    <add-menu-dialog ref="addMenuRef" @updateMenu="updateMenu"></add-menu-dialog>
  </div>
</template>
<script lang="ts">
import {
  getMenuList,
  addTwoMenu,
  deleteMenu,
  editMenu,
} from '../../api/menuTree'
import { defineComponent, reactive, ref, onBeforeMount, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import addMenuDialog from './addMenu/index.vue'
import { CirclePlus, DeleteFilled } from '@element-plus/icons'
interface form {
  name: string
  pid: string
  path: string
  icon: string
  order: string
}
export default defineComponent({
  components: {
    addMenuDialog,
    CirclePlus,
    DeleteFilled,
  },
  name: 'Menu',
  setup() {
    let menuTreeList = reactive<Array<any>>([]) //菜单数组
    const ruleFormRef = ref('ruleForm') //表单实列
    const addMenuRef = ref('addMenuRef') //新增菜单表单实列
    const editPid = ref(true) //控制pid的输入框的显示与隐藏
    const editPath = ref(false) //控制path输入框的显示与隐藏
    const ruleFormVisible = ref(false) //控制添加子级菜单的表单显示与隐藏
    const addValue = ref('新增子级菜单') //控制新增或修改
    // const defaultProps = reactive({
    //   children: 'children',
    //   label: 'name',
    // })
    //定义表单字段
    const ruleForm: form = reactive({
      name: '',
      pid: '',
      path: '',
      icon: '',
      order: '',
    })
    //表单校验
    const rules = {
      name: [
        {
          required: true,
          message: '请输入二级菜单名称',
          trigger: 'blur',
        },
      ],
      path: [
        {
          required: true,
          message: '请输入二级菜单路径',
          trigger: 'blur',
        },
      ],
    }
    //获取表单提交参数
    const getParams = () => {
      let params = {
        name: ruleForm.name,
        path: ruleForm.path,
        icon: ruleForm.icon,
        order: ruleForm.order,
      }
      if (addValue.value === '新增子级菜单') {
        params.pid = ruleForm.pid
      } else {
        params.id = ruleForm.pid
      }
      return params
    }
    //清空菜单重新获取
    const getAgainMenu = () => {
      ruleFormVisible.value = false
      menuTreeList.length = 0
      getMenu()
      location.reload() 
    }
    //新增表单事件
    const addMenuSave = async (params) => {
      const res = await addTwoMenu(params)
      if (res.data.code !== 200) {
        ElMessage({
          type: 'error',
          message: '新增失败',
        })
        return
      }
      ElMessage({
        type: 'success',
        message: '新增成功',
      })
      
      getAgainMenu()
    }
    //修改表单事件
    const editMenuSave = async (params) => {
      const res = await editMenu(params)
      if (res.data.code !== 200) {
        ElMessage({
          type: 'error',
          message: '修改失败',
        })
        return
      }
      ElMessage({
        type: 'success',
        message: '修改成功',
      })
      getAgainMenu()
    }
    //验证表单提交
    const submitForm = () => {
      const ruleFormRefValue: any = ruleFormRef.value
      ruleFormRefValue.validate(async (valid: boolean) => {
        if (!valid) return
        let params = {}
        switch (addValue.value) {
          case '新增子级菜单':
            params = getParams()
            addMenuSave(params)
            break
          case '修改菜单':
            params = getParams()
            editMenuSave(params)
          default:
            break
        }
      })
    }
    //重置表单
    const resetForm = () => {
      ruleForm.pid = ''
      ruleForm.name = ''
      ruleForm.path = ''
      ruleForm.icon = ''
      ruleForm.order = ''
      // ruleFormVisible.value = false
    }
    //新增一级菜单
    const addMenu = () => {
      const addMenuRefValue: any = addMenuRef.value
      addMenuRefValue.open()
    }
    //新增子级菜单
    const append = (id: string) => {
      resetForm()
      ruleForm.pid = id
      editPath.value = false
      ruleFormVisible.value = true
      nextTick(() => {
        const ruleFormRefValue: any = ruleFormRef.value
        ruleFormRefValue.clearValidate()
      })
      addValue.value = '新增子级菜单'
    }
    //删除菜单
    const remove = (id: any) => {
      console.log(id)
      ElMessageBox.confirm('确定要删除该菜单?', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await deleteMenu({
            id: id,
          })
          console.log(res)
          if (res.data.code !== 200) {
            ElMessage({
              type: 'error',
              message: '删除失败',
            })
            return
          }
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          menuTreeList.length = 0
          getAgainMenu()
          console.log(menuTreeList)
        })
        .catch(() => {})
    }
    //初始化菜单
    onBeforeMount(() => {
      getMenu()
    })
    const getMenu = async () => {
      // 获取菜单列表
      const { data } = await getMenuList()
      if (data.code === 200) {
        const result = data.data.result
        result.forEach((ele: any) => {
          menuTreeList.push(ele)
        })
      } else {
        ElMessage({
          message: data.message,
          type: 'error',
          offset: 330,
        })
      }
    }
    //树节点点击事件
    const handleNodeClick = (data: any) => {
      console.log(data)
      nextTick(() => {
        const ruleFormRefValue: any = ruleFormRef.value
        ruleFormRefValue.clearValidate()
      })
      ruleForm.pid = data.id
      ruleForm.name = data.name
      ruleForm.path = data.path
      ruleForm.icon = data.icon
      ruleForm.order = data.order
      editPath.value = true
      ruleFormVisible.value = true
      addValue.value = '修改菜单'
    }
    //更新菜单
    const updateMenu = () => {
      getAgainMenu()
    }
    return {
      menuTreeList,
      // defaultProps,
      ruleForm,
      rules,
      ruleFormRef,
      submitForm,
      resetForm,
      addMenu,
      addMenuRef,
      append,
      remove,
      getMenu,
      handleNodeClick,
      editPid,
      editPath,
      addValue,
      addMenuSave,
      editMenuSave,
      getParams,
      ruleFormVisible,
      getAgainMenu,
      updateMenu,
    }
  },
})
</script>
<style lang="scss" scoped>
.menu-tree {
  width: 300px;
  height: 740px;
}
.tree-form {
  display: flex;
  height: 800px;
}
.demo-ruleForm {
  background-color: #fff;
  margin-left: 20px;
  width: 500px;
  padding: 15px;
}
.btn {
  text-align: center;
}
.add-menu {
  height: 60px;
  display: flex;
  background-color: #fff;
  justify-content: space-between;
  align-items: center;
}
.menu-list {
  margin-left: 20px;
}
.add {
  margin-right: 20px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.add-icon {
  margin-right: 10px;
  color: skyblue;
}
.delete-icon {
  color: #ff3b30;
}
.addForm {
  text-align: center;
  margin-bottom: 20px;
}
</style>
